package com.yxw.live_vod_backend_boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.live_vod_backend_boot.dto.BillingQueryDTO;
import com.yxw.live_vod_backend_boot.dto.BillingSetupDTO;
import com.yxw.live_vod_backend_boot.entity.YxBillingSetupEntity;
import com.yxw.live_vod_backend_boot.mapper.BillingSetupMapper;
import com.yxw.live_vod_backend_boot.service.BillingSetupService;
import com.yxw.live_vod_backend_boot.util.PageUtils;
import com.yxw.live_vod_backend_boot.util.UserUtil;
import com.yxw.live_vod_backend_boot.vo.BillingSetupVO;
import com.yxw.yxnet_cd_center.common.constant.CommonConstant;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 计费设置管理
 * @author xiexuxin
 * @date 2023-11-27
 */
@Service
public class BillingServiceImpl extends ServiceImpl<BillingSetupMapper, YxBillingSetupEntity> implements BillingSetupService {

    @Autowired
    private BillingSetupMapper billingSetupMapper;

    @Autowired
    private UserUtil userUtil;

    /**
     * 设置直播扣费规则
     * @param setupDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setupFeeDeductRatio(BillingSetupDTO setupDTO) {
        if (setupDTO.getStartTime() == null || setupDTO.getPerMinuteConsume() == null) {
            throw new BaseException("启播时长与直播扣费规则不能为空");
        }
        if (setupDTO.getStartTime() <= 0 && setupDTO.getPerMinuteConsume() <= 0) {
            throw new BaseException("启播时长与直播扣费规则值必须大于0");
        }
        YxBillingSetupEntity billingSetup = assembleBillingSetupEntity();
        billingSetup.setBillingType(CommonConstant.ONE);
        billingSetup.setStartTime(setupDTO.getStartTime());
        billingSetup.setPerMinuteConsume(setupDTO.getPerMinuteConsume());
        baseMapper.insert(billingSetup);
        updatePreviousBillingSetupStatus(billingSetup);
    }

    /**
     * 设置视频币兑换规则
     * @param videoCoin
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setupVideoCoinRatio(Integer videoCoin) {
        if (videoCoin == null || videoCoin <= 0) {
            throw new BaseException("videoCoin值不能为空且必须大于0");
        }
        YxBillingSetupEntity billingSetup = assembleBillingSetupEntity();
        billingSetup.setBillingType(CommonConstant.ZERO);
        billingSetup.setVideoCoin(videoCoin);
        baseMapper.insert(billingSetup);
        updatePreviousBillingSetupStatus(billingSetup);
    }

    /**
     * 设置点播空间大小
     * @param onDemandSpace
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setupOnDemandSpaceSize(Integer onDemandSpace) {
        if (onDemandSpace == null || onDemandSpace <= 0) {
            throw new BaseException("点播空间值不能为空且必须大于0");
        }
        YxBillingSetupEntity previousSetup = baseMapper.selectOne(Wrappers.<YxBillingSetupEntity>lambdaQuery()
                .eq(YxBillingSetupEntity::getBillingType, CommonConstant.TWO)
                .orderByDesc(YxBillingSetupEntity::getSetHour)
                .last("LIMIT 1"));
        if (previousSetup != null && onDemandSpace <= previousSetup.getOnDemandSpace()) {
            throw new BaseException("点播空间不能小于上一次设置的值");
        }
        YxBillingSetupEntity billingSetup = assembleBillingSetupEntity();
        billingSetup.setBillingType(CommonConstant.TWO);
        billingSetup.setOnDemandSpace(onDemandSpace);
        baseMapper.insert(billingSetup);
        updatePreviousBillingSetupStatus(billingSetup);
    }


    private YxBillingSetupEntity assembleBillingSetupEntity() {
        YxBillingSetupEntity billingSetup = new YxBillingSetupEntity();
        billingSetup.setStatus(CommonConstant.ZERO);
        billingSetup.setSetHour(new Date());
        billingSetup.setSetUserId(userUtil.getLoginUserVo().getUserId());
        billingSetup.setSetUserName(userUtil.getLoginUserVo().getUserName());
        return billingSetup;
    }

    /**
     * 保持最新一条数据状态为启用,其他数据禁用
     * @param billingSetup
     */
    private void updatePreviousBillingSetupStatus(YxBillingSetupEntity billingSetup) {
        LambdaUpdateWrapper<YxBillingSetupEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.ne(YxBillingSetupEntity::getBillingSetupId, billingSetup.getBillingSetupId())
                .eq(YxBillingSetupEntity::getBillingType, billingSetup.getBillingType())
                .set(YxBillingSetupEntity::getStatus, CommonConstant.ONE);
        baseMapper.update(null, updateWrapper);
    }

    /**
     * 获取计费设置列表
     * @return
     */
    @Override
    public PageVO<BillingSetupVO> getBillingSetupList(BillingQueryDTO dto) {
        Page<BillingSetupVO> page = new Page<>(dto.getCurrPage(),dto.getPageSize());
        List<BillingSetupVO> list = billingSetupMapper.getBillingSetupList(page,dto);
        return PageUtils.get(page, list);
    }

    /**
     * 获取直播扣除视频币规则
     * @return
     */
    @Override
    public int getFeeDeductRatio() {
        LambdaQueryWrapper<YxBillingSetupEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YxBillingSetupEntity::getStatus, CommonConstant.ZERO)
                .eq(YxBillingSetupEntity::getBillingType, CommonConstant.ONE);
        List<YxBillingSetupEntity> billingSetupEntityList = baseMapper.selectList(queryWrapper);
        int perMinuteConsume = 0;
        if (1 == billingSetupEntityList.size()){
            for (YxBillingSetupEntity entity : billingSetupEntityList){
                perMinuteConsume = entity.getPerMinuteConsume();
            }
        }else {
            throw new BaseException("获取直播扣费比例失败,服务器忙,请稍后尝试!");
        }
        return perMinuteConsume;
    }

    @Override
    public int getVideoCoinRatio() {
        LambdaQueryWrapper<YxBillingSetupEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YxBillingSetupEntity::getStatus, CommonConstant.ZERO)
                .eq(YxBillingSetupEntity::getBillingType, CommonConstant.ZERO);
        List<YxBillingSetupEntity> billingSetupEntityList = baseMapper.selectList(queryWrapper);
        int videoCoin = 0;
        if (1 == billingSetupEntityList.size()){
            for (YxBillingSetupEntity entity : billingSetupEntityList){
                videoCoin = entity.getVideoCoin();
            }
        }else {
            throw new BaseException("获取直播扣费比例失败,服务器忙,请稍后尝试!");
        }
        return videoCoin;
    }

    @Override
    public int getOnDemandSpaceSize() {
        LambdaQueryWrapper<YxBillingSetupEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YxBillingSetupEntity::getStatus, CommonConstant.ZERO)
                .eq(YxBillingSetupEntity::getBillingType, CommonConstant.TWO);
        List<YxBillingSetupEntity> billingSetupEntityList = baseMapper.selectList(queryWrapper);
        int onDemandSpace = 0;
        if (1 == billingSetupEntityList.size()){
            for (YxBillingSetupEntity entity : billingSetupEntityList){
                onDemandSpace = entity.getOnDemandSpace();
            }
        }else {
            throw new BaseException("获取直播扣费比例失败,服务器忙,请稍后尝试!");
        }
        return onDemandSpace;
    }


}
